// 数字千位格式化
export const formatNum = (num, pure = false, permission = 0) => {
  if (num === "" || num < 0 || (!num && num !== 0) || permission == 1) {
    return "--";
  }
  if (num >= 0 && num < 1000) {
    return num;
  } else if (num >= 1000 && num < 10000) {
    return num.toLocaleString();
  } else {
    if (pure) {
      return (num / 10000).toFixed(2) + "万";
    } else {
      return (num / 10000).toFixed(2);
    }
  }
};

// 数字格式化成k为单位
export const thousandNumFormat = (num) => {
  if (num) {
    if (num >= 0 && num < 1000) {
      return num;
    } else {
      return (num / 1000).toFixed(1) + "k";
    }
  } else {
    return 0;
  }
};

// 识别图片是否为脏数据
export const isUrlUseful = (url) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      resolve(true); // 图像URL可以被src识别
    };
    img.onerror = () => {
      resolve(false); // 无法识别
    };
    img.src = url;
  });
};

// 递归返回多级数组中属性值为name对象的value属性的属性值
export const findValue = (arr, name) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children !== "") {
      const children = arr[i].children;
      for (let j = 0; j < children.length; j++) {
        if (children[j].name === name) {
          return children[j].value;
        } else if (children[j].children) {
          const nestedValue = findValue(children[j].children, name); // 递归调用
          if (nestedValue) {
            return nestedValue;
          }
        }
      }
    }
  }
  return null;
};

// 处理时间格式
export const formatDateTime = (dateTimeString) => {
  if (dateTimeString) {
    dateTimeString = dateTimeString.replace(/-/g, "/"); // 适配低版本ios显示NaN问题
    const dateTime = new Date(dateTimeString);
    const year = dateTime.getFullYear();
    const month = String(dateTime.getMonth() + 1).padStart(2, "0");
    const day = String(dateTime.getDate()).padStart(2, "0");
    const formattedDate = `${year}年${month}月${day}日`;
    return formattedDate;
  } else {
    return "";
  }
};

// 时间戳转年月日
export const timestampToYMD = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = ("0" + (date.getMonth() + 1)).slice(-2);
  const day = ("0" + date.getDate()).slice(-2);
  return `${year}年${month}月${day}日`;
};

// 获取url中的参数
export const getUrlParams = (name, url = window.location.href) => {
  url = url.split("?")[1];
  const urlParams = new URLSearchParams(url);
  const params = Object.fromEntries(urlParams.entries());
  console.log(">>>> query params >>>>", params);
  return params[name] ? params[name] : null;
};

// h5跳转至新开容器
export const JumpNewContainer = (path, queryString = "") => {
  let url = `${window.location.origin}${window.location.pathname}#/${path}/?airules=01-00&${queryString}`;
  const JumpNewContainerUrl = `https://esales-local/ask_bob#visit?encodeJumpUrl=${encodeURIComponent(
    url
  )}`;
  console.log(">>>> Jump跳转url >>>>", JumpNewContainerUrl);
  return JumpNewContainerUrl;
};

// 等宽瀑布流 （入参为单一模块的父级容器类名，图片加载完成后执行)
export const waterfall = (wrap = "van-list") => {
  // 获取容器宽度
  let contentEl = document.querySelector(`.${wrap}`);
  let contentElWidth = contentEl.offsetWidth;
  console.log(">>>> contentElWidth >>>>", contentElWidth);

  // 获取单个模块的宽度
  let itemEl = contentEl.children[0];
  let itemElWidth = itemEl.offsetWidth;
  console.log(">>>> itemElWidth >>>>", itemElWidth);

  // 计算第一行可以排列多少模块向下取整
  let columns = Math.floor(contentElWidth / itemElWidth);
  console.log(">>>> columns >>>>", columns);

  // 获取每行每个模块的高度组成的数组，初始值为第一行
  let arrHeight = [];
  for (let i = 0; i < contentEl.children.length; i++) {
    if (i < columns) {
      console.log(">>>> contentEl.children[i] >>>>", contentEl.children[i]);
      console.log(
        ">>>> contentEl.children[i].firstChild >>>>",
        contentEl.children[i].firstChild
      );
      arrHeight.push(contentEl.children[i].firstChild.offsetHeight); // 用数组收集第一行每个模块contentEl.children[i]的内容高度
    } else {
      let minHeight = Math.min(...arrHeight); // 找到高度最短的模块用于布置下一行
      let minIndex = arrHeight.indexOf(minHeight);
      contentEl.style.position = "relative";
      contentEl.children[i].style.position = "absolute";
      contentEl.children[i].style.left =
        contentEl.children[minIndex].offsetLeft + "px";
      contentEl.children[i].style.top = minHeight + "px";
      // 布置完成替换掉上一行的最小高度
      arrHeight[minIndex] =
        minHeight + contentEl.children[i].firstChild?.offsetHeight;
    }
    // console.log(">>>> arrHeight >>>>", arrHeight);
  }
};

// 防抖
export const debounce = (func, duration = 500) => {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, duration);
  };
};

// 判断当前环境
export const current_env = () => {
  return window.location.host === "salescmscdn.pa18.com" ? "prd" : "stg";
};
